//@ sourceURL=core-item-script-detail.js
Gikam.jQuery.fn.extend({
    "insertValueInFocus": function (value) {

        var dthis = Gikam.jQuery(this)[0]; // 将jQuery对象转换为DOM元素

        // IE下
        if (document.selection) {

            Gikam.jQuery(dthis).focus(); // 输入元素textara获取焦点
            var fus = document.selection.createRange();// 获取光标位置
            fus.text = value.text; // 在光标位置插入值
            Gikam.jQuery(dthis).focus(); // /输入元素textara获取焦点

            fus.moveStart('character', 0);
            fus.collapse(true);
            fus.select();

        }
        // 火狐下标准
        else if (dthis.selectionStart || dthis.selectionStart == '0') {

            var start = dthis.selectionStart;
            var end = dthis.selectionEnd;
            var top = dthis.scrollTop;

            // 以下这句，应该是在焦点之前，和焦点之后的位置，中间插入我们传入的值
            dthis.value = dthis.value.substring(0, start) + value.text + dthis.value.substring(end, dthis.value.length);

            Gikam.jQuery(dthis).focus();

            var focusPosition = start + value.text.length;
            dthis.setSelectionRange(focusPosition, focusPosition);

        }

        // 在输入元素textara没有定位光标的情况
        else {
            this.value += value.text;
            this.focus();
        }

        return Gikam.jQuery(this);
    }
});

limsTest.purposeFormulaDetailPage = {

    getBtnToolbar: function () {
        var _this = this;
        return {
            type: 'btnToolbar',
            items: [{
                type: 'button',
                text: 'GIKAM.BUTTON.CONFIRM',
                class: 'blue',
                icon: 'save',
                color: 'white',
                onClick: function () {
                    if (_this.form.validate()) {
                        var formData = _this.form.getData();
                        var saveData = {
                            id: formData.id,
                            formula: formData.formula
                        };
                        Gikam.put(limsProductMainPupose.baseUrl + '/instant', Gikam.getJsonWrapper({}, ['limsProductMainPuposeServiceImpl', [saveData]])).done(function () {
                            Gikam.getLastModal().close();
                        });
                    }
                }
            }, {
                type: 'button',
                text: 'GIKAM.BUTTON.CANCEL',
                icon: 'back',
                onClick: function () {
                    Gikam.getLastModal().close();
                }
            }]
        }
    },

    getScriptTabParam: function () {
        var _this = this;
        return {
            type: 'tab',
            shrink: false,
            panels: [{
                title: 'CORE.MODULE.SCRIPT.TESTS.TAB.SCRIPT',
                items: [{
                    type: 'btnGroup',
                    margin: '10px 10px 0px 5px',
                    items: [{
                        type: 'button',
                        id: 'core-product-purpose-script-detail-add-button',
                        text: '+',
                        onClick: function () {
                            _this.insertCalcFormula("+");
                        },
                        onRendered: function () {
                            Gikam.jQuery('#core-product-purpose-script-detail-add-button').find('.button').css('color', '#007aff');
                        }
                    }, {
                        type: 'button',
                        text: '-',
                        id: 'core-product-purpose-script-detail-sub-button',
                        onClick: function () {
                            _this.insertCalcFormula("-");
                        },
                        onRendered: function () {
                            Gikam.jQuery('#core-product-purpose-script-detail-sub-button').find('.button').css('color', '#007aff');
                        }
                    }, {
                        type: 'button',
                        text: '×',
                        id: 'core-product-purpose-script-detail-mul-button',
                        onClick: function () {
                            _this.insertCalcFormula("*");
                        },
                        onRendered: function () {
                            Gikam.jQuery('#core-product-purpose-script-detail-mul-button').find('.button').css('color', '#007aff');
                        }
                    }, {
                        type: 'button',
                        text: '÷',
                        id: 'core-product-purpose-script-detail-div-button',
                        onClick: function () {
                            _this.insertCalcFormula("/");
                        },
                        onRendered: function () {
                            Gikam.jQuery('#core-product-purpose-script-detail-div-button').find('.button').css('color', '#007aff');
                        }
                    }, {
                        type: 'button',
                        text: '>',
                        id: 'core-product-purpose-script-detail-1-button',
                        onClick: function () {
                            _this.insertCalcFormula(">");
                        },
                        onRendered: function () {
                            Gikam.jQuery('#core-product-purpose-script-detail-1-button').find('.button').css('color', '#007aff');
                        }
                    }, {
                        type: 'button',
                        text: '<',
                        id: 'core-product-purpose-script-detail-3-button',
                        onClick: function () {
                            _this.insertCalcFormula("<");
                        },
                        onRendered: function () {
                            Gikam.jQuery('#core-product-purpose-script-detail-3-button').find('.button').css('color', '#007aff');
                        }
                    }, {
                        type: 'button',
                        text: 'return',
                        id: 'core-product-purpose-script-detail-4-button',
                        onClick: function () {
                            _this.insertCalcFormula("return");
                        },
                        onRendered: function () {
                            Gikam.jQuery('#core-product-purpose-script-detail-4-button').find('.button').css('color', '#007aff');
                        }
                    }]
                }, {
                    type: 'form',
                    columns: 1,
                    id: 'core-product-purpose-script-detail-form',
                    url: limsProductMainPupose.baseUrl + '/' + _this.param.id,
                    titleWidth: 5,
                    fields: [{
                        field: 'formula',
                        type: 'textarea',
                        height: 420,
                        validators: [{type: 'unique', rule: limsTest.baseUrl + '/action/validate-formul'}],
                        onChange: function (field, value) {
                            _this.loadTestData();
                        }
                    }],
                    autoSave: false,
                    onRendered: function () {
                        _this.form = this;
                    },
                    onLoadSuccess: function (data) {
                        _this.loadTestData();
                    }
                }]
            }]
        };
    },

    getFuncGridParam: function () {
        var _this = this;
        return {
            type: 'tab',
            shrink: false,
            panels: [{
                title: 'CORE.MODULE.SCRIPT.TESTS.TAB.FUNC',
                items: [{
                    type: 'grid',
                    titleAlign: 'left',
                    generalButtonGroup: false,
                    id: 'core-product-purpose-script-detail-func-grid',
                    columns: [{
                        field: 'func',
                        title: 'T_CORE_ITEM.FUNC'
                    }],
                    page: false,
                    onRendered: function () {
                        this.loadData([{
                            func: 'if () else'
                        }, {
                            func: 'eq(a,b) #a等于b'
                        }, {
                            func: 'eql(a,b) #a等于b忽略大小写'
                        }, {
                            func: 'ct(a,b) #a包含b'
                        }, {
                            func: 'ctl(a,b) #a包含b忽略大小写'
                        }, {
                            func: 'NN(ob) #判定ob是否为空'
                        }, {
                            func: 'ln(double) #取对数，e为底数 '
                        }, {
                            func: 'lg(double) #取对数，10为底数'
                        }]);

                        Gikam.jQuery('#core-product-purpose-script-detail-func-grid').find('.toolbar,.grid-header').css('display', 'none');

                    },
                    onCellClick: function (field, row) {
                        if (_this.param.readonly !== 'true') {
                            _this.insertCalcFormula(row.func);
                        }
                    }
                }]
            }]
        };
    },

    getTestGridParam: function () {
        var _this = this;
        return {
            type: 'tab',
            shrink: false,
            panels: [{
                title: 'CORE.MODULE.SCRIPT.TESTS.TAB.TEST',
                items: [{
                    type: 'grid',
                    titleAlign: 'left',
                    generalButtonGroup: false,
                    id: 'core-product-purpose-script-detail-test-grid',
                    page: false,
                    columns: [{
                        field: 'selector',
                        width: 284,
                        title: 'T_CORE_ITEM.ITEM'
                    }, {
                        field: 'value',
                        title: 'T_CORE_ITEM.VALUE',
                        editor: true,
                    }],
                    toolbar: [{
                        type: 'button',
                        icon: 'pass',
                        text: 'CORE.MODULE.SCRIPT.TESTS.BUTTON.TEST',
                        onClick: function () {
                            var selectorData = Gikam.getComp('core-product-purpose-script-detail-test-grid').getData();

                            var script = _this.form.getData().formula;
                            if (!_this.form.validate()) {
                                return;
                            }
                            if (!Gikam.isEmpty(selectorData) && !Gikam.isEmpty(script)) {

                                var valiateFlag = true;
                                Gikam.each(selectorData, function (index, selector) {
                                    if (Gikam.isEmpty(selector.value)) {
                                        Gikam.alert('CORE.MODULE.SCRIPT.TESTS.TIP.VALUE_EMPTY');
                                        valiateFlag = false;
                                        return false;
                                    }
                                });

                                if (!valiateFlag) {
                                    return;
                                }

                                Gikam.postText(limsTest.baseUrl + '/items/action/test-script', Gikam.getJsonWrapper({
                                    script: script
                                }, ['', selectorData])).done(function (result) {
                                    Gikam.alert('result=' + (Gikam.isEmpty(result) ? 'null' : result));
                                });

                            }

                        }
                    }]
                }]
            }, {
                title: 'CORE.MODULE.SCRIPT.TESTS.TAB.FUNC_REMARK',
                items: [{
                    type: 'form',
                    columns: 1,
                    id: 'core-product-purpose-script-detail-func-remark',
                    fields: [{
                        field: 'remark',
                        type: 'textarea',
                        height: '600',
                        onChange: function (field, value) {
                            _this.loadTestData();
                        }
                    }],
                    onRendered: function () {
                        this.setData({
                            remark: "注意： 字符串请用 \"\" 包裹\n" +
                                "功能描述： \n" +
                                "1、RN(XX):获取当前检测任务下的XX检测项的值，返回数值\n" +
                                "2、RS(XX):获取当前检测任务下的XX检测项的值，返回字符串\n" +
                                "3、SN(XX):获取当前样本的XX属性值，返回数值\n" +
                                "4、SS(XX):获取当前样本的XX属性值，返回字符串\n" +
                                "\n" +
                                "一、判断 分析项CT，大于30阴性，否则阳性\n" +
                                "示例1：三目运算\n" +
                                "RN(\"CT\") > 30? \"阴性\":\"阳性\"\n" +
                                "\n" +
                                "示例2：普通if else\n" +
                                "if(RN(\"CT\") > 30) {\n" +
                                "  return \"阴性\";\n" +
                                "} else {\n" +
                                "  return \"阳性\";\n" +
                                "}\n" +
                                "\n" +
                                "二、样本是质控类型的，CT大于20阴性，否则阳性；样本类型其他的，CT大于30阴性，否则阳性\n" +
                                "示例1：三目运算\n" +
                                "ctl(SS(\"sampleType\"),\"质控\") ? (RN(\"CT\") > 20? \"阴性\":\"阳性\") : (RN(\"CT\") > 30? \"阴性\":\"阳性\")\n" +
                                "\n" +
                                "示例2：普通if else\n" +
                                "if(ctl(SS(\"sampleType\"),\"质控\")){\n" +
                                "  if(RN(\"CT\") > 20) {\n" +
                                "    return \"阴性\";\n" +
                                "  } else {\n" +
                                "    return \"阳性\";\n" +
                                "  }\n" +
                                "} else {\n" +
                                "  if(RN(\"CT\") > 30) {\n" +
                                "    return \"阴性\";\n" +
                                "  } else {\n" +
                                "    return \"阳性\";\n" +
                                "  }\n" +
                                "}"
                        });
                        Gikam.jQuery('#core-product-purpose-script-detail-func-remark').find('.textarea .readonly-text, .textarea textarea').css('background-color', '#ffffff').css('color', '#fafcfb');
                    },
                }]
            }]
        };
    },

    getRemarkGridParam: function () {
        var _this = this;
        return {
            type: 'tab',
            shrink: false,
            panels: [{
                title: 'CORE.MODULE.SCRIPT.TESTS.TAB.FUNC_REMARK',
                items: [{
                    type: 'form',
                    columns: 1,
                    id: 'core-product-purpose-script-detail-func-remark',
                    fields: [{
                        field: 'remark',
                        type: 'textarea',
                        height: '600',
                        onChange: function (field, value) {
                            _this.loadTestData();
                        }
                    }],
                    onRendered: function () {
                        this.setData({
                            remark: "注意： 字符串请用 \"\" 包裹\n" +
                                "功能描述： \n" +
                                "1、RN(XX):获取当前检测任务下的XX检测项的值，返回数值\n" +
                                "2、RS(XX):获取当前检测任务下的XX检测项的值，返回字符串\n" +
                                "3、SN(XX):获取当前样本的XX属性值，返回数值\n" +
                                "4、SS(XX):获取当前样本的XX属性值，返回字符串\n" +
                                "\n" +
                                "一、判断 分析项CT，大于30阴性，否则阳性\n" +
                                "示例1：三目运算\n" +
                                "RN(\"CT\") > 30? \"阴性\":\"阳性\"\n" +
                                "\n" +
                                "示例2：普通if else\n" +
                                "if(RN(\"CT\") > 30) {\n" +
                                "  return \"阴性\";\n" +
                                "} else {\n" +
                                "  return \"阳性\";\n" +
                                "}\n" +
                                "\n" +
                                "二、样本是质控类型的，CT大于20阴性，否则阳性；样本类型其他的，CT大于30阴性，否则阳性\n" +
                                "示例1：三目运算\n" +
                                "ctl(SS(\"sampleType\"),\"质控\") ? (RN(\"CT\") > 20? \"阴性\":\"阳性\") : (RN(\"CT\") > 30? \"阴性\":\"阳性\")\n" +
                                "\n" +
                                "示例2：普通if else\n" +
                                "if(ctl(SS(\"sampleType\"),\"质控\")){\n" +
                                "  if(RN(\"CT\") > 20) {\n" +
                                "    return \"阴性\";\n" +
                                "  } else {\n" +
                                "    return \"阳性\";\n" +
                                "  }\n" +
                                "} else {\n" +
                                "  if(RN(\"CT\") > 30) {\n" +
                                "    return \"阴性\";\n" +
                                "  } else {\n" +
                                "    return \"阳性\";\n" +
                                "  }\n" +
                                "}"
                        });
                        Gikam.jQuery('#core-product-purpose-script-detail-func-remark').find('.textarea .readonly-text, .textarea textarea').css('background-color', '#ffffff').css('color', '#fafcfb');
                    },
                }]
            }]
        };
    },

    loadTestData: function () {
        var script = Gikam.getComp('core-product-purpose-script-detail-form').getData().formula;

        if (!Gikam.isEmpty(script)) {
            var regex = /RN\([^()]*\)|RS\([^()]*\)|SN\([^()]*\)|SS\([^()]*\)/g;
            var selectorArray = script.match(regex);

            if (Gikam.isEmpty(selectorArray)) {
                return;
            }
            var testData = [];
            var distinctSelectorArray = [];
            selectorArray.map(function (selector) {
                if (distinctSelectorArray.indexOf(selector) < 0) {
                    distinctSelectorArray.push(selector);
                    testData.push({
                        selector: selector
                    });
                }
            });
            Gikam.getComp('core-product-purpose-script-detail-test-grid').loadData(testData);
        }

    },

    insertCalcFormula: function (content) {
        var _this = this;

        if (content.indexOf('if ()') >= 0) {
            content = 'if () {\r\n\r\n} else {\r\n\r\n}';
        }

        if (content.indexOf('#') >= 0) {
            content = content.split("#")[0];
        }

        var scriptTextArea = Gikam.jQuery('#core-product-purpose-script-detail-form').find("textarea[name='formula']");
        scriptTextArea.insertValueInFocus({
            "text": content
        });

        _this.form.setData({
            formula: scriptTextArea.val()
        });

        _this.loadTestData();
    },

    getSelectorGridParam: function () {
        var _this = this;
        return {
            type: 'tab',
            shrink: false,
            panels: [{
                title: 'CORE.MODULE.SCRIPT.TESTS.TAB.SELECTOR',
                items: [{
                    type: 'grid',
                    titleAlign: 'left',
                    generalButtonGroup: false,
                    id: 'core-product-purpose-script-detail-selector-grid',
                    page: false,
                    columns: [{
                        field: 'selector',
                        title: 'T_CORE_ITEM.SELECTOR'
                    }],
                    onRendered: function () {
                        this.loadData([{
                            type: 'purpose',
                            selector: Gikam.propI18N('T_CORE_ITEM.ITEM_SELECTOR')
                        }, {
                            type: 'sampleItem',
                            selector: Gikam.propI18N('T_CORE_ITEM.SAMPLEINFO_SELECTOR')
                        }]);

                        Gikam.jQuery('#core-product-purpose-script-detail-selector-grid').find('.toolbar,.grid-header').css('display', 'none');

                    },
                    onCellClick: function (field, row) {
                        // 加载选择器页面
                        _this.loadSelectorPage(row.type);

                    }
                }]
            }]
        };
    },

    loadSelectorPage: function (selector) {
        var _this = this;

        var url = limsTest.baseUrl + '/page/script-selector';
        var title = Gikam.propI18N('T_CORE_ITEM.ITEM_SELECTOR');
        if (selector === 'sampleItem') {
            title = Gikam.propI18N('T_CORE_ITEM.SAMPLEINFO_SELECTOR');
        }
        Gikam.create('modal', {
            width: 600,
            height: 400,
            title: title,
            url: url + Gikam.param({
                type: selector,
                testId: _this.param.testId,
                itemId: _this.param.id
            }),
            onAfterClose: function (expression) {
                if (!Gikam.isEmpty(expression)) {
                    _this.insertCalcFormula(expression);

                }
            }
        });

    },

    createPage: function () {
        Gikam.create('layout', {
            renderTo: Gikam.getLastModal().window.$dom,
            center: {
                items: [{
                    type: 'layout',
                    west: {
                        width: '160',
                        items: [{
                            type: 'layout',
                            north: {
                                height: '50%',
                                items: [this.getFuncGridParam()]
                            },
                            center: {
                                items: [this.getSelectorGridParam()]
                            }
                        }]
                    },
                    center: {
                        items: [{
                            type: 'layout',
                            center: {
                                items: [this.getBtnToolbar(), this.getScriptTabParam()]
                            }
                        }]
                    },
                    east: {
                        width: '30%',
                        items: [{
                            type: 'layout',
                            center: {
                                // height : '35%',
                                items: [this.getTestGridParam()]
                            },
                            /*center : {
                                height : '300',
                                items : [ this.getRemarkGridParam() ]
                            }*/
                        }]
                    },
                }]
            },
        });
    },

    init: function (param) {
        this.param = param;

        this.createPage();
    }
}
